package com.leo.erp.web.depotitem;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.leo.erp.dto.DepotItemExecution;
import com.leo.erp.service.DepotItemService;
import com.leo.erp.util.GlobalRuntimeException;
import com.leo.erp.util.HttpServletRequestUtil;
import com.leo.erp.util.Tools;

@Controller
@RequestMapping(value = "/depotItem")
public class DepotItemManagementController {
	@Autowired
	private DepotItemService depotItemService;
	
	/**
	 * 根据商品id和仓库id查询库存数量
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/findStockNumById")
	@ResponseBody
	public Map<String, Object> findStockNumById(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		//获取前台传过来的值
		int depotId = HttpServletRequestUtil.getInt(request, "depotId");
		int materialId = HttpServletRequestUtil.getInt(request, "mId");
		int tenantId = Integer.parseInt(request.getSession().getAttribute("tenantId").toString());
		DepotItemExecution de = depotItemService.getStockByParam(depotId, materialId, null, null, tenantId);
		modelMap.put("success", true);
		modelMap.put("stock", de.getKucun());
		
		return modelMap;
	}
	
	@RequestMapping(value = "/buyOrSalePrice")
	@ResponseBody
	public Map<String, Object> buyOrSalePrice(HttpServletRequest request){
		Map<String, Object> modelMap = new HashMap<>();
		String message = "成功";
		try {
			Date date = new Date();
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
			String dateString = formatter.format(date);
			List<String> list = Tools.getSixMonth(dateString);
			modelMap.put("monthList", list);
			List<BigDecimal> buyPriceList = new ArrayList<>();
			for(String month : list) {
				BigDecimal outPrice = depotItemService.inOrOutPrice("入库", "采购", month);
				BigDecimal inPrice = depotItemService.inOrOutPrice("出库", "采购退货", month);
				buyPriceList.add(outPrice.subtract(inPrice));
			}
			modelMap.put("buyPriceList", buyPriceList);
			List<BigDecimal> salePriceList = new ArrayList<>();
			for(String month : list) {
				BigDecimal outPrice = depotItemService.inOrOutPrice("出库", "采购", month);
				BigDecimal inPrice = depotItemService.inOrOutPrice("入库", "采购退货", month);
				salePriceList.add(outPrice.subtract(inPrice));
			}
			modelMap.put("salePriceList", salePriceList);
			modelMap.put("success", true);
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
			message = "统计失败";
			modelMap.put("success", false);
			modelMap.put("msg", message);
		}
		
		return modelMap;
	}
	
}
